# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from rest_framework import viewsets
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.serializers import GoodsSerializer
from course.models import Course
from user.models import User
from .models import Goods, UserCourse,Orders
from goods.utils import get_order_id, get_pay_url, alipay



class GoodsCourseViewSet(viewsets.ModelViewSet):
    """
    完成产品的增删改查
    """
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer  # 优先使用 get_serializer_class 返回的序列化器

    # 指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序

    # 指定排序字段, 不设置, 排序功能不起效
    # ordering_fields = ('date_joined', 'id')

    # 指定过滤字段, 不设置, 过滤功能不起效
    filter_fields = ('course', 'pay_type', 'is_putaway')


class PayUrlView(APIView):
    # permission_classes = (IsAuthenticated,)

    def post(self, request):
        """
        course_id: 课程id
        type_id: 购买渠道,  1. 普通, 2. 促销

        :param request:
        :return:
        """
        # 1. 获取课程id,获取购买途径(普通购买, 促销购买) 获取用户
        c_id = request.data.get('c_id')
        print(c_id)
        # 获取对应的商品id
        goods_course = Goods.objects.filter(course_id=c_id).first()

        if not goods_course:

            return Response({'code':403,'msg':'商品未存在'})

        print(goods_course.id)

        user_id = request.data.get('user_id')
        
        user = User.objects.filter(id=user_id).first()
        print(user.username)
        # 2. 下定单
        order_id = get_order_id()
        print(order_id)
        order = Orders(user=user, goods=goods_course, order_id=order_id, pay_method=1, status=1,
                       total_amount=goods_course.price)
        order.save()

        # 3. 根据订单 生成支付链接
        subject = "实验楼订单:%s, 价格:%s" % (order.order_id, order.total_amount)
        pay_url = get_pay_url(order.order_id, order.total_amount, subject)

        # 4. 返回链接
        return Response({"code": 0, "msg": "下单成功", "data": {"pay_url": pay_url}})

class PayMentView(APIView):
    # permission_classes = (AllowAny,)

    def post(self, request):

        data = request.data

        sign = data.pop('sign')

        success = alipay.verify(data, sign)
        #
        if not success:
            return Response({"code": 999, "msg": "非法请求"})
        # 跟新订单状态
        order = Orders.objects.get(order_id=data['out_trade_no'])
        order.trade_no = data['trade_no']
        order.pay_time = data['timestamp']
        order.status = 2
        order.save()

        goods = order.goods
        UserCourse(user=order.user, goods_course=goods).save()

        return Response({"code": 200, "msg": "购买成功"})




